// 用来判断是用户自己进入的报工页面，还是插件进入的报工页面
var baseToken
console.log(chrome)
// 判断是否到时间提醒报工人了
var mainTimer
maxTimer()
function maxTimer () {
  clearInterval(mainTimer)
  mainTimer = setInterval(() => {
    chrome.storage.sync.get(['weekTime', 'usr', 'psw', 'num', 'ids'], async res => {
      console.log(res)
      if (!res.weekTime) {
        alert('请完善配置后，再次刷新此插件！')
        return
      }
      if (new Date().getHours() >= res.weekTime.split(':')[0] && new Date().getMinutes() >= res.weekTime.split(':')[1]) {
        if (!res.num) chrome.storage.sync.set({ num: -1 })
        if (!Array.isArray(res.ids)) chrome.storage.sync.set({ ids: [] })
        // chrome.notifications.create('1998', {
        //   type: 'basic',
        //   title: '快下班了铁子。',
        //   message: '什么时候填报工？(请勿连续点击按钮，否则将创建多个tab页)',
        //   iconUrl: '/img/what.jpg',
        //   buttons: [{ title: '现在填', iconUrl: '/img/ok.png' }, { title: '不用你操心', iconUrl: '/img/wait.png' }]
        // })
        let tokenRes = await getToken({ loginName: res.usr, passWord: res.psw })
        if (!tokenRes.status) msg(tokenRes.message)
        baseToken = tokenRes.data.uuid
        let ids = await getDayId(tokenRes.data.userId)
        chrome.storage.sync.set({ ids, userId: tokenRes.data.userId }, async _ => {
          if (ids.length == 2) await update()
          else await insert()
          clearInterval(mainTimer)
        })
      }
    })

  }, 1000 * 60)
}

var cardTimer = setInterval(() => {
  if (new Date().getHours() >= 17 && new Date().getMinutes() >= 39) {
    chrome.notifications.create('', {
      type: 'basic',
      title: '快下班了，不要忘记打卡！！！',
      message: '漏一次扣50😒, 请现在立马打开钉钉！',
      iconUrl: '/img/card.png'
    })
    clearInterval(cardTimer)
  }
}, 1000 * 60)



function getCurrentTabId () {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      resolve(tabs.length ? tabs[0].id : null)
    })
  })
}




async function getDayId (userId) {
  let recordDate = new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
  let dateStr = small(new Date().getMonth() + 1) + '-' + small(new Date().getDate())
  let res = await db('https://www.sgwl.com:4431/sgoa/record/queryCalendar', 'post', { userId, recordDate })
  let flterList = res.data.filter(v => {
    return v.end.indexOf(dateStr) > -1 && v.id
  })
  let ids = flterList.map(v => v.id)
  return ids
}

function getToken (data) {
  return db('https://www.sgwl.com:4431/sgoa/user/login', 'post', data)
}

function insert () {
  chrome.storage.sync.get(['userId', 'num', 'checkInfoIdx', 'infoArr'], async function (result) {
    let recordDate = new Date().getFullYear() + '-' + small(new Date().getMonth() + 1) + '-' + small(new Date().getDate())
    for (let i = 1; i <= 2; i++) {
      let res = await db('https://www.sgwl.com:4431/sgoa/record/insert', 'post', { userId: result.userId, deptIds: 14, recordDate, recordType: i, times: 4, projectId: result.num, content: result.infoArr[result.checkInfoIdx].title, taskId: '' })
      if (i == 2) alert(res.message + '，报工程序已执行完毕！')
    }

  })
}

function update () {
  chrome.storage.sync.get(['userId', 'num', 'checkInfoIdx', 'ids', 'infoArr'], async function (result) {
    for (let i = 0; i < result.ids.length; i++) {
      let res = await upFn({ userId: result.userId, id: result.ids[i], times: 4, projectId: result.num, content: result.infoArr[result.checkInfoIdx].title, taskId: '' })
      if (i == result.ids.length - 1) alert(res.message + '，报工程序已执行完毕！')
    }

  })
}
function msg (title) {
  chrome.notifications.create('over', {
    type: 'basic',
    title,
    message: '来自栋老师的提示',
    iconUrl: '/img/over.jpg'
  })
}
function upFn (data) {
  return db('https://www.sgwl.com:4431/sgoa/record/update', 'post', data)
}
function small (val) {
  return val < 10 ? ('0' + val) : val
}
// function bToken (str) {
//   str(res => {
//     baseToken = res
//   })
// }

function db (url, type, data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url,
      type,
      dataType: 'json',
      data,
      headers: {
        token: baseToken
      },
      success (res) { resolve(res) },
      error (err) { reject(err) }
    })
  })

}